﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using Adex;
using Telerik.Web.UI;
using SubSonic.Sugar;
using System.Security;
using MediaMonitor.Common;


 public partial class users_report_press_paged : Adex.BasePage
{
    //DateTime sDate = Convert.ToDateTime("01/01/2000"), eDate = Convert.ToDateTime("01/01/2000");
    int mediaTypeCode = 0;
    string mediaCodes = "";
    int programCode = 0;
    int sectorCode = 0, subSectorCode = 0, subSector2Code = 0,  categoryCode = 0;
    int advertiserCode = 0, brandCode = 0, productCode = 0, versionCode = 0, agencyCode = 0;
    int sTime = 0, eTime = 0;
    int sCol = 0, eCol = 0;
    int colorCode = 0;
    int sInch = 0, eInch = 0;
    int pageNumber = 0;
    int sPrice = 0, ePrice = 0;
    bool firstAppearanceOnly = false;
    string cols="";

    protected void Page_Init(object sender, EventArgs e) {
         
    }


    protected void Page_Load(object sender, EventArgs e)
    {
       
    }

    private void PrepareGridColumns(string cols) {

       

            radGrid.Columns.FindByUniqueName("RFDate").Visible = cols.Contains("RFDate");
            radGrid.Columns.FindByUniqueName("MediaType").Visible = cols.Contains("MediaTypeName");
            radGrid.Columns.FindByUniqueName("Media").Visible = cols.Contains("MediaName");
            radGrid.Columns.FindByUniqueName("Program").Visible = cols.Contains("ProgramName");

            radGrid.Columns.FindByUniqueName("Sector").Visible = cols.Contains(" SectorName"); //a space before sectorname to keep a difference from SubSectorName 
            radGrid.Columns.FindByUniqueName("SubSector").Visible = cols.Contains("SubSectorName");
            radGrid.Columns.FindByUniqueName("Category").Visible = cols.Contains("CategoryName");

            radGrid.Columns.FindByUniqueName("Media").Visible = cols.Contains("MediaName");
            radGrid.Columns.FindByUniqueName("Agency").Visible = cols.Contains("AgencyName");
            radGrid.Columns.FindByUniqueName("Advertiser").Visible = cols.Contains("AdvertiserName");
            radGrid.Columns.FindByUniqueName("Brand").Visible = cols.Contains("BrandName");
            radGrid.Columns.FindByUniqueName("Product").Visible = cols.Contains("ProductName");
            radGrid.Columns.FindByUniqueName("ProdVersion").Visible = cols.Contains("ProdVersionName");
            radGrid.Columns.FindByUniqueName("STime").Visible = cols.Contains("TimeStartFormatted");
            radGrid.Columns.FindByUniqueName("ETime").Visible = cols.Contains("TimeEndFormatted");

            radGrid.Columns.FindByUniqueName("PressBodyCode").Visible = cols.Contains("PressBodyCode");
            radGrid.Columns.FindByUniqueName("ColorCode").Visible = cols.Contains("ColorCode");    
            radGrid.Columns.FindByUniqueName("ClassCode").Visible = cols.Contains("ClassCode");
            radGrid.Columns.FindByUniqueName("Wide").Visible = cols.Contains("Wide");
            radGrid.Columns.FindByUniqueName("Length").Visible = cols.Contains("Length");
            radGrid.Columns.FindByUniqueName("PageNumber").Visible = cols.Contains("PageNumber");
            
            radGrid.Columns.FindByUniqueName("RealCost").Visible = cols.Contains("RealCost"); 
           
            lnkGrp_Adv.Visible = cols.Contains("AdvertiserName");
            lnkGrp_Agnc.Visible = cols.Contains("AgencyName");
            lnkGrp_Brnd.Visible = cols.Contains("BrandName");
            lnkGrp_Prod.Visible = cols.Contains("ProductName");
            lnkGrp_Media.Visible = cols.Contains("MediaName");
            //lnkGrp_Prog.Visible = cols.Contains("ProgramName");


    }

    protected void radGrid_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
    {
        string sDate =  Utility.GetRequestedVal("sd", "01_01_2000").Replace("_", "/");
        string eDate =  Utility.GetRequestedVal("ed", "01_01_2000").Replace("_", "/");
 
        mediaTypeCode = Utility.ToInt(Utility.GetRequestedVal("mtc", "0"));
       
        bool searchFromAllMedia = Utility.ToBool(Utility.GetRequestedVal("mc", "false"));
        mediaCodes = searchFromAllMedia == false ? Session["SearchMediaCodes_press"].ToString() : "" ;
         
        programCode = Utility.ToInt(Utility.GetRequestedVal("prg", "0"));

        sectorCode = Utility.ToInt(Utility.GetRequestedVal("s", "0"));
        subSectorCode = Utility.ToInt(Utility.GetRequestedVal("ss", "0"));
        categoryCode = Utility.ToInt(Utility.GetRequestedVal("cc", "0"));

        advertiserCode = Utility.ToInt(Utility.GetRequestedVal("adv", "0"));
        brandCode = Utility.ToInt(Utility.GetRequestedVal("brnd", "0"));
        productCode = Utility.ToInt(Utility.GetRequestedVal("prod", "0"));
        versionCode = Utility.ToInt(Utility.GetRequestedVal("ver", "0"));
        agencyCode = Utility.ToInt(Utility.GetRequestedVal("agn", "0"));

        sTime = Utility.ToInt(Utility.GetRequestedVal("st", "0"));
        eTime = Utility.ToInt(Utility.GetRequestedVal("et", "0"));



        sCol = Utility.ToInt(Utility.GetRequestedVal("scol", "0"));
        eCol = Utility.ToInt(Utility.GetRequestedVal("ecol", "0"));

        colorCode = Utility.ToInt(Utility.GetRequestedVal("ccode", "0"));
        sInch = Utility.ToInt(Utility.GetRequestedVal("sin", "0"));
        eInch = Utility.ToInt(Utility.GetRequestedVal("ein", "0"));
        pageNumber = Utility.ToInt(Utility.GetRequestedVal("pn", "0"));

        sPrice = Utility.ToInt(Utility.GetRequestedVal("sp", "0"));
        ePrice = Utility.ToInt(Utility.GetRequestedVal("ep", "0"));

        firstAppearanceOnly = Utility.ToBool(Utility.GetRequestedVal("fa", "0"));

        cols = Utility.GetRequestedVal("cols", "ProdVersionCode, ProductCode, ProdVersionName, ProductName, Price");

        cols = "MediaTypeCode, ProdVersionCode, ProductCode, PressFile, NewPressFile, " + cols;

        if (sDate != "1/1/2000" || eDate != "1/1/2000")
            cols = "RFDate, " + cols;

        if (!firstAppearanceOnly)
        {
           // cols += ", ShortVideo, FullVideo, ShortVideoFile, FullVideoFile, Duration, Price";
            cols += ", Price";
        }
        else
        {
            cols = cols.Replace("RFDate,", "");
            //cols += ", RFDate, ShortVideo, FullVideo, ShortVideoFile, FullVideoFile, Duration, Price";
            cols += ", RFDate, Price";
        }

        cols += ", PressFile";

       // DataTable dt = SPs.GetReportPress(AppUser.CurrUserID, cols, AppUser.GetCountry(), Utility.ToDateTime(sDate), Utility.ToDateTime(eDate), mediaTypeCode, mediaCodes, programCode, sectorCode, subSectorCode, subSector2Code, categoryCode, advertiserCode, brandCode, productCode, versionCode, agencyCode, sTime, eTime, sCol, eCol, colorCode, pageNumber, sInch, eInch, sPrice, ePrice, firstAppearanceOnly).GetDataSet().Tables[0];


        //(int startRow, int pageSize, int userID, int countryID, DateTime sDate, DateTime eDate, int mediaTypeCode, string mediaCodes, int sectorCode, int subSectorCode, int subSector2Code, int categoryCode, int advertiserCode, int brandCode, int productCode, int prodVersionCode, int agencyCode, int sPrice, int ePrice, bool fa

         objDS.SelectParameters["userID"].DefaultValue = AppUser.CurrUserID.ToString();
         objDS.SelectParameters["countryID"].DefaultValue = AppUser.GetCountry().ToString() ;
         objDS.SelectParameters["sDate"].DefaultValue =  sDate.ToString() ;
         objDS.SelectParameters["eDate"].DefaultValue =  eDate.ToString();
         objDS.SelectParameters["mediaTypeCode"].DefaultValue =  mediaTypeCode.ToString();
         objDS.SelectParameters["mediaCodes"].DefaultValue =  mediaCodes ;
         objDS.SelectParameters["sectorCode"].DefaultValue = sectorCode.ToString() ;
         objDS.SelectParameters["subSectorCode"].DefaultValue = subSectorCode.ToString();
         objDS.SelectParameters["subSector2Code"].DefaultValue = subSector2Code.ToString();
         objDS.SelectParameters["categoryCode"].DefaultValue = categoryCode.ToString();
         objDS.SelectParameters["advertiserCode"].DefaultValue = advertiserCode.ToString();
         objDS.SelectParameters["brandCode"].DefaultValue = brandCode.ToString();
         objDS.SelectParameters["productCode"].DefaultValue = productCode.ToString();
         objDS.SelectParameters["prodVersionCode"].DefaultValue = versionCode.ToString();
         objDS.SelectParameters["agencyCode"].DefaultValue = agencyCode.ToString();
         objDS.SelectParameters["sPrice"].DefaultValue =  sPrice.ToString() ;
         objDS.SelectParameters["ePrice"].DefaultValue = ePrice.ToString();
         objDS.SelectParameters["fa"].DefaultValue = firstAppearanceOnly.ToString(); 

        radGrid.DataSourceID = "objDS";
         
        //radGrid.DataSource = dt; 
        PrepareGridColumns(cols);
        
    }

     

    protected void ObjDS_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
    {
        if (!e.ExecutingSelectCount)
        {
            e.Arguments.MaximumRows = radGrid.PageSize;
            e.InputParameters.Add("e", e);
        } 
    }


    protected void radGrid_PreRender(object sender, EventArgs e)
    {
        //foreach (GridDataItem dataItem in radGrid.Items)
        //{
        //    if ((dataItem.OwnerTableView.Name == "Report"))
        //    {
        //        ////Merge rows 
        //         GridTableView tv = (GridTableView)dataItem.OwnerTableView;
        //         for (int rowIndex = tv.Items.Count - 1; rowIndex >= 0; rowIndex--)
        //        {
        //           GridDataItem row = tv.Items[rowIndex];
        //           //GridDataItem previousRow = tv.Items[rowIndex + 1];

        //           //row["Advertiser"].Text = Strings.CamelToProper(row["Advertiser"].Text.ToLower());
        //           //row["Agency"].Text = SubSonic.Sugar.Strings.CamelToProper(row["Agency"].Text.ToLower());
        //           //row["Brand"].Text = SubSonic.Sugar.Strings.CamelToProper(row["Brand"].Text.ToLower());
        //           //row["Product"].Text = SubSonic.Sugar.Strings.CamelToProper(row["Product"].Text.ToLower());
        //           //row["Program"].Text = SubSonic.Sugar.Strings.CamelToProper(row["Program"].Text.ToLower());
                    

        //        //    #region Advertiser
                   

        //        //    if (row["Advertiser"].Text == previousRow["Advertiser"].Text)
        //        //    {
        //        //        row["Advertiser"].RowSpan = previousRow["Advertiser"].RowSpan < 2 ? 2 : previousRow["Advertiser"].RowSpan + 1;
        //        //        previousRow["Advertiser"].Visible = false;
        //        //        previousRow["Advertiser"].Text = "&nbsp;";
        //        //    }

        //        //    #endregion

        //        //    #region Agency

        //        //    if (row["Agency"].Text == previousRow["Agency"].Text)
        //        //    {
        //        //        row["Agency"].RowSpan = previousRow["Agency"].RowSpan < 2 ? 2 : previousRow["Agency"].RowSpan + 1;
        //        //        previousRow["Agency"].Visible = false;
        //        //        previousRow["Agency"].Text = "&nbsp;";
        //        //    }


        //        //    #endregion

        //        //    #region Brand

        //        //    if (row["Brand"].Text == previousRow["Brand"].Text)
        //        //    {
        //        //        row["Brand"].RowSpan = previousRow["Brand"].RowSpan < 2 ? 2 : previousRow["Brand"].RowSpan + 1;
        //        //        previousRow["Brand"].Visible = false;
        //        //        previousRow["Brand"].Text = "&nbsp;";
        //        //    }


        //        //    #endregion

        //        //    #region Product

        //        //    if (row["Product"].Text == previousRow["Product"].Text)
        //        //    {
        //        //        row["Product"].RowSpan = previousRow["Product"].RowSpan < 2 ? 2 : previousRow["Product"].RowSpan + 1;
        //        //        previousRow["Product"].Visible = false;
        //        //        previousRow["Product"].Text = "&nbsp;";
        //        //    }


        //        //    #endregion

        //        //    #region Media

        //        //    if (row["Media"].Text == previousRow["Media"].Text)
        //        //    {
        //        //        row["Media"].RowSpan = previousRow["Media"].RowSpan < 2 ? 2 : previousRow["Media"].RowSpan + 1;
        //        //        previousRow["Media"].Visible = false;
        //        //        previousRow["Media"].Text = "&nbsp;";
        //        //    }


        //        //    #endregion

        //        //    #region Program

        //        //    if (row["Program"].Text == previousRow["Program"].Text)
        //        //    {
        //        //        row["Program"].RowSpan = previousRow["Program"].RowSpan < 2 ? 2 : previousRow["Program"].RowSpan + 1;
        //        //        previousRow["Program"].Visible = false;
        //        //        previousRow["Program"].Text = "&nbsp;";
        //        //    }


        //        //    #endregion

        //        }
        //    }
        //}
    }

    protected void radGrid_ItemCommand(object source, GridCommandEventArgs e)
    {
        if (e.CommandName == "Add2Cart") {

            int pvCode = Utility.ToInt(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ProdVersionCode"].ToString());
            int pdCode = Utility.ToInt(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ProductCode"].ToString());
            decimal price = Utility.ToDecimal(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["Price"]);
            string pressFile = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["NewPressFile"].ToString();

            hdnPV.Value = pvCode.ToString();
            hdnPD.Value = pdCode.ToString();
            hdnPrice.Value=price.ToString();
            hdnPressFile.Value = pressFile;

            

            int existingOrderWithSameItem = Cart.FindOrderByProdVersion(pvCode, AppUser.CurrUserID);

            if (existingOrderWithSameItem > 0) {
                string warningMsg = "The video you want to purchase is already present in your Order #<b>" + existingOrderWithSameItem.ToString() + "</b>.<br><br> Do you still want to purchas this video?";
                 ltrWarningOrderNum.Text = warningMsg;
                 pnl.Visible = true;
                }
            else{
                Add2Cart(pvCode, pdCode, price, pressFile);
                //ShowPop(this.Page, false);

            }


        }//end Add2Cart
    }

    private void Add2Cart(int pvCode, int pdCode, decimal price, string pressFile) {
         
        
        VProdVersion pv = new VProdVersion("ProdVersionCode", pvCode);

        string pvName = pv.ProdVersionName;
        string pdName = pv.ProductName;
        string svf = Utility.ToStr(pv.ShortVideoFile); 

        string fvf = Utility.ToStr(pv.FullVideoFile); 

        bool sv = Utility.ToBool(pv.ShortVideo); 

        bool fv = Utility.ToBool(pv.FullVideo);

        string prFile = pressFile;
        string odFile = "";

        string rdFile = "";
        string cbFile = "";

        int mtCode = Utility.ToInt(MediaType.Query().SetSelectList("MediaTypeCode").WHERE("MediaTypeName", "Press").ExecuteScalar());

        if (Cart.AddItem(Cart.CreateCartItem(mtCode, pvCode, pvName, pdCode, pdName, price, svf, fvf, sv, fv, prFile, odFile, rdFile, cbFile)) == true)
        {
            AjaxFuncs.MsgBox(this.Page, "Selected video added to your cart successfully");
        }
        else
        {
            AjaxFuncs.MsgBox(this.Page, "Already added to your cart");
        }

    }


    protected void lnkGrp_Clicked(object sender, EventArgs e) {
    
        
       LinkButton lnk = ((LinkButton)(sender));
       string grp = lnk.CommandArgument;

       if (lnk.Text.StartsWith("Group"))
       {
           //radGrid.MasterTableView.GroupByExpressions.Add(new GridGroupByExpression(grp + " Group By " + grp));
           radGrid.MasterTableView.GroupLoadMode = GridGroupLoadMode.Server;
           radGrid.MasterTableView.GroupsDefaultExpanded = true;

            radGrid.MasterTableView.GroupByExpressions.Add(grp + " Group By " + grp);
            lnk.ForeColor = System.Drawing.Color.Red;
            lnk.Font.Bold = true;
            lnkClearGroup.Visible = true;
       }
        
       radGrid.Rebind();
          
    }

    protected void lnkClearGroup_Clicked(object sender, System.EventArgs e)
    {
        radGrid.MasterTableView.GroupByExpressions.Clear();
        radGrid.Rebind();

        lnkGrp_Adv.ForeColor = lnkGrp_Agnc.ForeColor = lnkGrp_Brnd.ForeColor = lnkGrp_Media.ForeColor = lnkGrp_Prod.ForeColor  = System.Drawing.Color.PowderBlue;
        
        lnkGrp_Adv.Font.Bold = lnkGrp_Agnc.Font.Bold = lnkGrp_Brnd.Font.Bold = lnkGrp_Media.Font.Bold=lnkGrp_Prod.Font.Bold =  true;

        lnkClearGroup.Visible = false;
    }
    

     protected void btnExport_Clicked(object sender, EventArgs e){
         
        radGrid.MasterTableView.ExportToExcel(); 
     }

     protected void btnCancelPurchase_Clicked(object sender, EventArgs e) {
         pnl.Visible = false;
     }

     protected void btnContinuePurchase_Clicked(object sender, EventArgs e)
     {
         pnl.Visible = false;
         Add2Cart(Utility.ToInt(hdnPV.Value), Utility.ToInt(hdnPD.Value), Utility.ToDecimal(hdnPrice.Value), hdnPressFile.Value) ;

       
     }

     public static void ShowPop(Page aspxPage, bool show)
     {
         try
         {

             AjaxControlToolkit.ModalPopupExtender screen = (AjaxControlToolkit.ModalPopupExtender)aspxPage.FindControl("MPE");


             if ((screen == null))
                 return;

             if (show == true)
             {
                 screen.Show();

             }
             else
             {
                 screen.Hide();
             }
         }
         catch
         {
         }
     }
}